package test;

import bean.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;

/**
 * @Author Clarklevis
 * @Date 2021/5/14
 */
public class Demo {

    public static void main(String[] args) {
        //java-->json
        Users aaa = new Users(11, "aaa", "123456", 123.456);
        JSONObject jsonObject = JSONObject.fromObject(aaa);
        System.out.println(jsonObject);


        //json-->java
        String str = "{\"money\":123.456,\"password\":\"123456\",\"uid\":11,\"username\":\"aaa\"}";
        JSONObject jsonObject1 = JSONObject.fromObject(str);//从其他类型的Object生成JSON对象
        Object o = JSONObject.toBean(jsonObject1, Users.class);//从JSON对象生成Bean对象
        System.out.println(o);

        //java 集合-->json
        ArrayList<Users> list = new ArrayList<>();
        list.add(new Users(1,"张三","123",12.34));
        list.add(new Users(2,"张三1","12323",12.564));
        list.add(new Users(3,"张三2","12233",12.3664));
        list.add(new Users(4,"张三3","123333",12.3224));
        JSONArray jsonArray = JSONArray.fromObject(list);
        System.out.println(jsonArray);


        //json--->java集合
        String str2 = "[{\"money\":12.34,\"password\":\"123\",\"uid\":1,\"username\":\"张三\"},{\"money\":12.564,\"password\":\"12323\",\"uid\":2,\"username\":\"张三1\"},{\"money\":12.3664,\"password\":\"12233\",\"uid\":3,\"username\":\"张三2\"},{\"money\":12.3224,\"password\":\"123333\",\"uid\":4,\"username\":\"张三3\"}]\n";
        JSONArray jsonArray1 = JSONArray.fromObject(str2);
        Object[] o1 = (Object[]) JSONArray.toArray(jsonArray1, Users.class);
        for (Object o2 : o1) {
            System.out.println(o2);
        }


    }

}
